package com.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.web.entity.RecognitionHistory;
import com.web.mapper.RecognitionHistoryMapper;
import com.web.service.RecognitionHistoryService;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class RecognitionHistoryServiceImpl extends ServiceImpl<RecognitionHistoryMapper, RecognitionHistory>
        implements RecognitionHistoryService {

    @Override
    public IPage<RecognitionHistory> getHistoryList(Long userId, int page, int size, String type, String keyword,String imageUrl) {
        Page<RecognitionHistory> pageParam = new Page<>(page, size);
        QueryWrapper<RecognitionHistory> wrapper = new QueryWrapper<>();

        wrapper.eq("user_id", userId);

        // 按类型筛选
        if (StringUtils.isNotBlank(type) && !"all".equals(type)) {
            wrapper.eq("type", type);
        }

        // 按关键词搜索
        if (StringUtils.isNotBlank(keyword)) {
            wrapper.and(w -> w.like("result", keyword)
                    .or().like("english_name", keyword)
                    .or().like("location", keyword));
        }
        // 按 imageUrl 过滤
        if (StringUtils.isNotBlank(imageUrl)) {
            wrapper.like("image_url", imageUrl);
        }

        wrapper.orderByDesc("create_time");
        return this.page(pageParam, wrapper);
    }

    @Override
    public RecognitionHistory getHistoryDetail(Long id) {
        return this.getById(id);
    }

    @Override
    public boolean deleteHistory(Long id, Long userId) {
        QueryWrapper<RecognitionHistory> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id).eq("user_id", userId);
        return this.remove(wrapper);
    }

    @Override
    public boolean clearAllHistory(Long userId) {
        QueryWrapper<RecognitionHistory> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return this.remove(wrapper);
    }

    @Override
    public Map<String, Object> getUserStats(Long userId) {
        return baseMapper.getUserStats(userId);
    }

    @Override
    public RecognitionHistory saveRecognitionResult(RecognitionHistory history) {
        this.save(history);
        return history;
    }
}
